<?php

namespace app\api\service;

use app\store\model\User;
use Hashids\Hashids;
use think\facade\Db;

class UserService
{

    /**
     * 添加分销关系
     */
    public function addShip($pid, $uid, $store_id)
    {
        $p_info = Db::name('user_auth')->where('id', $pid)->value('id');
        $u_info = Db::name('user_auth')->where('id', $uid)->value('id');
        if ($uid != $pid && !empty($p_info) && !empty($u_info)) {
            $isPid = Db::name('user_level')->where('user_id', $uid)->where('level', 1)->find();
            if (empty($isPid)) { //不存在上级
                //查找我的下级中是否存在上级用户
                $isExitPid = Db::name('user_level')->where('parent_user_id', $uid)->where('user_id', $pid)->value('id');
                //查父类的上级中是否存在自己
                $isExitUid = Db::name('user_level')->where('user_id', $pid)->where('parent_user_id', $uid)->value('id');
                if (empty($isExitPid) && empty($isExitUid)) {
                    //查找我的所有下级
                    $list = Db::name('user_level')->where('parent_user_id', $uid)->order('level', 'asc')->select();
                    $add_s = ['user_id' => $uid, 'store_id' => $store_id, 'parent_user_id' => $pid, 'level' => 1, 'ctime' => time()];
                    //查找父类的上级
                    $list1 = Db::name('user_level')->where('user_id', $pid)->order('level', 'asc')->select();
                    $ret1 = [$add_s];
                    $ret2 = [];
                    foreach ($list as $k => $v) {
                        $temp1 = ['user_id' => $v['user_id'], 'store_id' => $store_id, 'parent_user_id' => $pid, 'level' => $v['level'] + 1, 'ctime' => time()];
                        array_push($ret1, $temp1);
                    }
                    if (!empty($list1)) {
                        foreach ($ret1 as $k => $v) {
                            foreach ($list1 as $k1 => $v1) {
                                $temp2 = ['user_id' => $v['user_id'], 'store_id' => $store_id, 'parent_user_id' => $v1['parent_user_id'], 'level' => $v['level'] + 1 + $k1, 'ctime' => time()];
                                array_push($ret2, $temp2);
                            }
                        }
                    }
                    $ret = array_merge($ret1, $ret2);
                    $rest = Db::name('user_level')->insertAll($ret);
                    return $rest;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 绑定手机号
     */
    public function bindPhone($data, $uid)
    {
        $rst = Db::name('user_auth')->where('id', $uid)->update(['phone' => $data['phone']]);
        return $rst;
    }

    /**
     * 修改密码
     */
    public function resetPassword($data, $uid)
    {
        $password = password_hash($data['password'], PASSWORD_DEFAULT);
        $rst = Db::name('user_auth')->where('id', $uid)->update(['password' => $password]);
        return $rst;
    }

    /**
     * 微信登录
     * */
    public function wxLogin($param)
    {
        $user_id = Db::name('user_auth')
            ->where('open_id', $param['open_id'])
            ->value('id');

        if (!empty($user_id)) {
            return $user_id;
        }

        $user_id = $this->register($param);
        if (!empty($user_id)) {
            return $user_id;
        }

        return 0;

    }

    /**
     * 支付宝登录
     * */
    public function aliLogin($param)
    {
        $user_id = Db::name('user_auth')
            ->where('phone', $param['phone'])
            ->value('id');

        if (!empty($user_id)) {
            return $user_id;
        }

        $user_id = $this->register($param);
        if (!empty($user_id)) {
            return $user_id;
        }

        return 0;
    }

    /**
     * 手机号验证码登录
     */
    public function phoneCodeLogin($param)
    {
        $user_id = Db::name('user_auth')
            ->where('phone', $param['phone'])
            ->value('id');

        if (!empty($user_id)) {
            return $user_id;
        }

        $user_id = $this->register($param);
        if (!empty($user_id)) {
            return $user_id;
        }

        return 0;
    }

    /**
     *
     * 手机号登录
     * */
    public function phoneLogin($param)
    {

        $user = Db::name('user_auth')
            ->field('id,phone,password')
            ->where(['phone' => $param['phone'], 'store_id' => $param['store_id']])
            ->find();

        return !empty($user) ? $user : [];
    }

    /**
     * 用户信息统计
     * */

    public static function getUserTotalInfo($user_id)
    {

        $group_starting_count = Db::name('group_activity_record')->where(['user_id' => $user_id, 'status' => 1])->count('id');
        $group_success_count = Db::name('group_activity_record')->where(['user_id' => $user_id, 'status' => 2])->count('id');
        $group_fail_count = Db::name('group_activity_record')->where(['user_id' => $user_id, 'status' => -1])->count('id');

        $user_info = Db::name('user')
            ->alias('a')
            ->field('a.avatar,a.nickname,a.integral,a.gold,a.balance,b.grade_name,a.birthday,a.gender')
            ->join('user_grade b', 'a.user_grade_id=b.id')
            ->where('a.user_id', $user_id)
            ->find();
        if (!empty($user_info)) {
            $is_bind_phone = Db::name('user_auth')->where('id', $user_id)->value('phone');
            $user_info['is_bind_phone'] = $is_bind_phone ? true : false;
        }
        return [
            'group_starting_count' => $group_starting_count,
            'group_success_count' => $group_success_count,
            'group_fail_count' => $group_fail_count,
            'user_info' => $user_info,
        ];
    }

    /**
     * 获取用户的商家推广码和代理推广码
     */
    public static function getPromotionCode($user_id)
    {
        $u_info = Db::name('user')->where('user_id', $user_id)->find();
        if (empty($u_info['invite_code'])) {
            $invite = new InviteService();
            $invite_code = $invite->id2Code($user_id);
            Db::name('user')->where('user_id', $user_id)->update(['invite_code'=>$invite_code]);
            return $invite_code;
        } 
        return $u_info['invite_code'];
    }

    /**
     * 余额明细
     * */
    public static function getBalanceDetail($user_id)
    {
        $balanceDetails = Db::name('user_balance_detail')
            ->field('change_desc,change_type,change_balance,change_time')
            ->where('user_id', $user_id)
            ->withAttr('change_time', function ($value) {
                return date('Y-m-d H:i:s', $value);
            })->order('change_time', 'desc')
            ->paginate();

        $total_balance = Db::name('user')->where('user_id', $user_id)->value('balance');

        return [
            'total_balance' => $total_balance,
            'balanceDetails' => $balanceDetails,
        ];
    }

    /**
     * 积分明细
     * */
    public static function getIntegralDetail($user_id)
    {
        $integralDetails = Db::name('user_integral_detail')
            ->field('change_desc,change_type,change_integral,change_time')
            ->where('user_id', $user_id)
            ->withAttr('change_time', function ($value) {
                return date('Y-m-d H:i:s', $value);
            })->order('change_time', 'desc')
            ->paginate();

        $total_integral = Db::name('user')->where('user_id', $user_id)->value('integral');

        return [
            'total_balance' => $total_integral,
            'integralDetails' => $integralDetails,
        ];
    }

    /**
     * 金豆明细
     * */
    public static function getGoldDetail($user_id)
    {
        $goldDetails = Db::name('user_gold_detail')
            ->field('change_desc,change_type,change_gold,change_time')
            ->where('user_id', $user_id)
            ->withAttr('change_time', function ($value) {
                return date('Y-m-d H:i:s', $value);
            })->order('change_time', 'desc')
            ->paginate();

        $total_gold = Db::name('user')->where('user_id', $user_id)->value('gold');

        return [
            'total_gold' => $total_gold,
            'goldDetails' => $goldDetails,
        ];
    }

    /**
     *
     * 用户手机号注册
     * */
    public function register($data)
    {
        $hashids = new Hashids('', 6);

        $parent_id = 0;
        if (!empty($data['invite_code'])) {
            $parent_id = $hashids->decode($data['invite_code']);
        }
        $user_grade_id = UserService::getStoreDefaultGrade($data['store_id']);
        Db::startTrans();
        try {
            $user_id = Db::name('user_auth')->insertGetId([
                'phone' => !empty($data['phone']) ? $data['phone'] : '',
                'password' => !empty($data['password']) ? password_hash($data['password'], PASSWORD_DEFAULT) : '',
                'open_id' => !empty($data['open_id']) ? $data['open_id'] : '',
                'store_id' => $data['store_id'],
                'ali_user_id' => !empty($data['ali_user_id']) ? $data['ali_user_id'] : '',
                'register_time' => time(),
            ]);
            // var_dump($data);exit;
            Db::name('user')->insert([
                'user_id' => $user_id,
                'user_grade_id' => $user_grade_id,
                'store_id' => $data['store_id'],
                'avatar' => !empty($data['avatar']) ? $data['avatar'] : '',
                'nickname' => !empty($data['nickname']) ? $data['nickname'] : '',
                'gender' => !empty($data['gender']) ? $data['gender'] : 0,
                'parent_id' => $parent_id,
            ]);
            if (!empty($parent_id)) {
                event('UserRegister', [$user_id, $parent_id]);
            }

            Db::commit();

            return $user_id;
        } catch (\Exception $e) {
            // echo $e->getMessage();exit;
            // 回滚事务
            Db::rollback();
            return null;
        }

    }

    /**
     * 获取店铺会员默认等级
     * */
    public static function getStoreDefaultGrade($store_id)
    {
        $grade_id = Db::name('user_grade')->where(['store_id' => $store_id, 'is_default' => 1])->value('id');

        return $grade_id;
    }

    /**
     *
     * 更新用户资料
     * */
    public function changeUser($user_id, $data)
    {

        $result = User::update($data, ['user_id' => $user_id]);
        //    echo User::getLastSql();exit;
        return $result;
    }

}
